<template>
  <div>
    <h1>作品管理</h1>
    <el-divider></el-divider>
    <div class="good-header">
      <el-button type="primary" @click="showDialog(0)" plain>添加作品</el-button>
      <el-button type="primary" @click="exFile" plain>导出到Excel</el-button>

      <div>
        <el-input placeholder="请输入作品名称关键字" v-model="name" @input="changeContent">
          <i slot="suffix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>
      <div>
        <el-select v-model="goodState" placeholder="请选择状态" @change="changeContent" clearable>
          <el-option label="已入库" value="0"></el-option>
          <el-option label="已出库" value="1"></el-option>
        </el-select>
      </div>
      <div>
        <el-select v-model="autherId" placeholder="请选择作者" clearable @change="changeContent">
          <el-option v-for="item in autherList" :key="item.id" :label="item.name"
                     :value="item.id"></el-option>
        </el-select>
      </div>

    </div>
    <el-divider></el-divider>
    <el-table :data="goodList" style="width: 100%" :header-cell-style="{ 'text-align': 'center' }"
              :cell-style="{ 'text-align': 'center' }">
      <el-table-column prop="id" label="#ID"></el-table-column>
      <el-table-column prop="name" label="作品名称"></el-table-column>
      <el-table-column prop="pic" label="图片">
        <template slot-scope="scope">
          <div @click="showPic(scope.row.pic)">
            <el-avatar shape="square" size="small" :src="scope.row.pic"></el-avatar>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="autherName" label="作者"></el-table-column>
      <el-table-column prop="size" label="尺寸"></el-table-column>
      <el-table-column prop="price" label="价格（￥）"></el-table-column>
      <el-table-column prop="state" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state==0" type="success">已入库</el-tag>
          <el-tag v-if="scope.row.state==1" type="info">已出库</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="入库时间"></el-table-column>
      <el-table-column prop="outTime" label="出库时间">
        <template slot-scope="scope">
          <span v-if="scope.row.state==1">{{ scope.row.outTime }}</span>
          <span v-else>尚未出库</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="140px">
        <template slot-scope="scope">
          <el-button type="primary" @click="showDialog(1,scope.row)" icon="el-icon-edit" size="small"
                     circle></el-button>
          <el-button type="success" icon="el-icon-upload2" v-if="scope.row.state==0" circle
                     @click="outGoodById(scope.row.id)"
                     size="small"></el-button>
          <el-button type="danger" icon="el-icon-delete" @click="removeGood(scope.row.id)" circle
                     size="small"></el-button>
        </template>
      </el-table-column>

      <el-image-viewer
          v-if="imgViewerVisible"
          :on-close="closeImgViewer"
          :url-list="imgList"/>

    </el-table>


    <el-pagination style="margin-top: 20px;"
                   background
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :current-page="pageNum"
                   :page-sizes="[10, 15, 20, 30,100]"
                   :page-size="pageSize"
                   layout="total, sizes, prev, pager, next, jumper"
                   :total="total">
    </el-pagination>

    <el-dialog :title="isAdd?'添加作品':'修改作品'" :visible.sync="dialogVisible" width="35%" @close="handleClose">
      <el-form ref="form" :model="good" label-width="80px">
        <el-form-item label="作品名称">
          <el-input v-model="good.name" placeholder="请输入作品名称"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="good.price" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item label="尺寸">
          <el-col :span="11">
            <el-input v-model="good.width" placeholder="请输入长度"></el-input>
          </el-col>
          <el-col :span="1">
            ×
          </el-col>
          <el-col :span="11">
            <el-input v-model="good.height" placeholder="请输入高度"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="作品名称">
          <el-select v-model="good.autherId" placeholder="请选择作者">
            <el-option v-for="item in autherList" :key="item.id" :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="作品图片">
          <el-upload class="avatar-uploader" action="http://localhost:3942/img/upload" :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button @click="handleSubmit" type="primary">{{ isAdd ? '添加' : '修改' }} </el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
import {listGoods, addGood, updateGood, delGood, outGood, exportFile} from "@/api/GoodApi";
import {listAllAuther} from "@/api/AutherApi";

export default {
  components: {
    'el-image-viewer': () => import('element-ui/packages/image/src/image-viewer')
  },
  data() {
    return {
      dialogVisible: false,
      goodList: [],
      pageNum: 1,
      pageSize: 10,
      autherId: '',
      name: '',
      total: 0,
      imgViewerVisible: false,//显示大图
      imgList: [],
      isAdd: true,
      good: {},
      imageUrl: '',
      autherList: [],
      goodState: '',
      isUpload: false
    }
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val
      this.getGoodsList()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.getGoodsList()
    },
    getGoodsList() {
      listGoods(this.pageNum, this.pageSize, this.autherId, this.name, this.goodState).then(res => {
        this.goodList = res.rows
        this.total = res.total
      }).catch(err => {
      })
    },
    showPic(pic) {
      this.imgViewerVisible = true;
      this.imgList.push(pic)
      const m = (e) => {
        e.preventDefault()
      };
      document.body.style.overflow = 'hidden';
      document.addEventListener("touchmove", m, false); // 禁止页面滑动
    },
    closeImgViewer() {
      this.imgViewerVisible = false;
      const m = (e) => {
        e.preventDefault()
      };
      document.body.style.overflow = 'auto';
      document.removeEventListener("touchmove", m, true);
    },
    handleClose() {
      this.good = {}
      this.imageUrl = ''
    },
    showDialog(val, good) {
      if (val == 0) {
        this.isAdd = true
      } else {
        this.isAdd = false
        this.imageUrl=good.pic
        this.good = good
      }
      this.dialogVisible = true
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = res.data;
    },
    beforeAvatarUpload(file) {
      this.isUpload = true
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!');
      }
      return isLt2M;
    },
    handleSubmit() {
      if (this.isAdd) {
        this.good.pic = this.imageUrl
        addGood(this.good).then(res => {
          this.$message.success("添加成功")
          this.dialogVisible = false
          this.getGoodsList()
        }).catch(err => {
          this.$message.error("添加失败")
        })
      } else {
        if (this.isUpload) {
          this.good.pic = this.imageUrl
          this.isUpload = false
        }
        updateGood(this.good).then(res => {
          this.$message.success("修改成功")
          this.dialogVisible = false
          this.getGoodsList()
        }).catch(err => {
          this.$message.error("修改失败")
        })
      }
    },
    changeContent() {
      this.pageNum = 1
      this.getGoodsList()
    },
    removeGood(id) {

      this.$confirm('此操作将永久删除该作品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delGood(id).then(res => {
          this.$message.success("删除成功")
          this.getGoodsList()
        }).catch(err => {
          this.$message.error("删除失败")
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    outGoodById(id) {
      this.$confirm('此操作将把该作品移出仓库, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        outGood(id).then(res => {
          this.$message.success("出库成功")
          this.getGoodsList()
        }).catch(err => {
          this.$message.error("出库失败")
        })
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消出库'
        });
      });
    },
    exFile() {
      exportFile().then(res => {
        this.$message.success("导出成功")
      }).catch(err => {
        this.$message.error("导出失败")
      })
    }
  },
  created() {
    this.getGoodsList()
    listAllAuther().then(res => {
      this.autherList = res
    }).catch(err => {
    })
  }
}
</script>

<style scoped lang="less">
.good-header {
  display: flex;

  div {
    width: 200px;
    margin-left: 20px;
  }
}

/deep/ .avatar-uploader .el-upload {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

/deep/ .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>